/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.odg.dg.runtimedata;

import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;
import org.opu.odg.dg.impl.DocumentGenerationContext;
import org.opu.odg.dg.incomingdata.ContentDescription;
import org.opu.odg.dg.incomingdata.ContextIteration;
import org.opu.odg.dg.runtimedata.VariableHolder;

/**
 *
 * @author yura
 */
public class Content implements Iterable<ContextIteration>, Closeable {

    private ContentDescription contentDescription;
    private String name;
    private Content parent;
    private DocumentGenerationContext context;
    private VariableHolder variableHolder;

    private ContextIteration lastIteration;

    public Content(ContentDescription contentDescription, String name,
            Content parent, DocumentGenerationContext context,
            VariableHolder variableHolder) {
        this.contentDescription = contentDescription.clone();
        this.name = name;
        this.parent = parent;
        this.context = context;
        this.variableHolder = variableHolder;
    }

    public String getName() {
        return name;
    }

    public Content getParent() {
        return parent;
    }

    public ContextIteration getLastIteration() {
        if (lastIteration == null) {
            throw new IllegalStateException(name + ": before call this method you have to call iterator");
        }

        return lastIteration;
    }

    public boolean isContextIterationAvailable() {
        return lastIteration != null;
    }
    
    @Override
    public Iterator<ContextIteration> iterator() {
        final Iterator<ContextIteration> iterator = contentDescription
                .asIterable(context, variableHolder).iterator();
        return new Iterator<ContextIteration>() {

            @Override
            public boolean hasNext() {
                return iterator.hasNext();
            }

            @Override
            public ContextIteration next() {
                return lastIteration = iterator.next();
            }

            @Override
            public void remove() {
                iterator.remove();
            }
        };
    }

    @Override
    public void close() throws IOException {
        contentDescription.close();
    }

}
